<?php
namespace Company\Controller;
use Think\Controller;

class AutoController extends Controller {
	//数据库配置
	public function erp_db($db_name){
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		C('db_config.DB_NAME',$db_name);
		//数据库连接基础配置-end
	}

	//全部推送()
	public function pushoms_all($times=1){
		$Model =M();
		$p=M('PushorderCron');
		$pc=M('PushorderCronDetail');
		$w=M('Warehouse');
		$p_info=$p->where(array('status'=>0))->order('add_time asc')->find();
		if(empty($p_info)){
			// file_put_contents('./log/cron/pushoms_all_cron'.date('Y-m-d').'.log',date('Y-m-d H:i:s')."没有推送任务".PHP_EOL,FILE_APPEND);//日志导出sql
			die;
		}
		$username=$p_info['username'];
		$warehouse_code=$p_info['warehouse_code'];
		$porder_id=$p_info['id'];
		$pc_sql="select order_id from t_pushorder_cron_detail where porder_id=".$porder_id." and status=0 order by add_time limit 0,20";
		// $pc_list=$pc->field('order_id')->where(array('porder_id'=>$porder_id,'status'=>0))->limit(20)->order('add_time')->select();
		$pc_list=$Model->query($pc_sql);
		
		if(empty($pc_list)){
			$pc_sql="select order_id from t_pushorder_cron_detail where porder_id=".$porder_id." and status=2 order by add_time limit 0,1";
			$pc_list=$Model->query($pc_sql);
			// $pc_list=$pc->field('order_id')->where(array('porder_id'=>$porder_id,'status'=>2))->limit(1)->order('add_time')->select();
		}
		if(empty($pc_list)){
			$p->where(array('id'=>$porder_id))->save(array('status'=>1));
			die;
		}
		$db_name=C('DB_PREFIX_T').$username;
		
		$ids=array();
		foreach($pc_list as $k=>$v){
			$ids[$k]=$v['order_id'];
		}
		$param=array();
		$param['ids']=$ids;
		$param['username']=$username;
		
		$warehouse_cate=$w->where(array('warehouse_code'=>$warehouse_code))->getField('warehouse_cate');
		
		if($username=='17012345699'){//澳洲定制
			$res=$this->pushoms_aozhou($param,$db_name);
		}else{
			if($warehouse_cate==1){//一般仓
				$res=$this->pushoms_normal_normal($param,$db_name);
			}
			if($warehouse_cate==2){//跨境仓
				$res=$this->pushoms_normal($param,$db_name);
			}
		}
		$this->erp_db($db_name);
		// $m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$Model_s =M('',C('DB_PREFIX_T'),C('db_config'));

		if($res['status']){
			$del_res=$pc->where(array('order_id'=>array('in',$ids)))->delete();
			file_put_contents('./log/cron/pushoms_all_error_times'.date('Y-m-d').'.log',date('Y-m-d H:i:s').'///'.var_export($times,true).PHP_EOL,FILE_APPEND);//日志导出sql
			if($times<20){
				// sleep(2);
				$this->pushoms_all(++$times);
			}
		}else{
			if(count($ids)==1){//是二次推送，则同步错误信息到erp，提示再次推送
			
				if($res['message']=='订单重复'){
					$del_res=$pc->where(array('order_id'=>array('in',$ids)))->delete();
					$res_sql="update erp_pushorder set push_status=1,cron_push_error='".$res['message']."' where id=".$ids[0];
					$res_delete=$Model_s->execute($res_sql);
				}else{
					//同步状态到erp-begin
					$res_sql="update erp_pushorder set push_status=0,cron_push_error='".$res['message']."' where id=".$ids[0];
					$res_delete=$Model_s->execute($res_sql);
					//同步状态到erp-end
					if($res_delete!==false){
						$del_res=$pc->where(array('order_id'=>array('in',$ids)))->delete();
					}
				}
				file_put_contents('./log/cron/pushoms_all_error_times11'.date('Y-m-d').'.log',date('Y-m-d H:i:s').'///'.var_export($times,true).PHP_EOL,FILE_APPEND);//日志导出sql
				file_put_contents('./log/cron/pushoms_all_error'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($res['message'],true).PHP_EOL,FILE_APPEND);//日志导出sql
				if($times<20){
					// sleep(2);
					$this->pushoms_all(++$times);
				}
			}else{
				$ids_string=implode(',',$ids);
				$sql="update t_pushorder_cron_detail set status=2,marker='".$res['message']."' where order_id in (".$ids_string.")";
				$Model->execute($sql);
			}
			file_put_contents('./log/cron/pushoms_all_123'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($res,true).PHP_EOL,FILE_APPEND);//日志导出sql
			// file_put_contents('./log/cron/pushoms_all_cron'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($pc->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
		}
    }
	
	//订单推送(澳洲)
	public function pushoms_aozhou($param=array(),$db_name){
		$this->erp_db($db_name);
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');
		file_put_contents('./log/cron/sql'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($m,true).PHP_EOL,FILE_APPEND);//日志导出sql
		file_put_contents('./log/cron/sql'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$ids=$param['ids'];
		$url="http://www.t-cang.com/oms/index.php/Api/Request/order_erp";

		$map['id']=array('in',$ids);
		$erp_code=$u->where(array('username'=>$param['username']))->getField('id');
		
		$list=$m->field("id,old_order_no order_no,user_name,user_phone,user_phone buyer_phone,user_idcard,buyer_idcard,buyer_name,apply_logistics,logiscompany_code,logistics_no,province user_province,erp_mark_mailno remark,$erp_code erp_code,city user_city,area user_area,user_address,pay_number,paycompany_code,discount,ems_fee,ems_fee order_freight,insure_amount,goods_tax,come_from,cod,cod_money,is_mall,alipay_out_trade_no,liandong_apply_no")->where($map)->select();
		// echo $m->getlastsql();
		file_put_contents('./log/cron/sql'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($m->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
		//错误料号9344949001140/9344949001287修正计数器-begin
		$m_e=M('CountView',C('DB_PREFIX_T'),C('db_config'));
		$err_count=$m_e->where(array('id'=>1))->getField('count');
		//错误料号9344949001140/9344949001287修正计数器-end
		if(empty($list)){
			$return['message']='没有找到数据';
			$return['status']=false;
			return $return;
		}
		foreach($list as $k=>$v){
			if(empty($v['buyer_idcard'])){
				$list[$k]['buyer_idcard']=$v['user_idcard'];
			}
			$list[$k]['order_detail']=$g->field('goods_no goods_sn,goods_name,goods_nums,goods_price,goods_batch_no')->where(array('order_id'=>$v['id']))->select();
			$total_price=0;//订单总价格
			$order_tax=0;//订单总税金
			foreach($list[$k]['order_detail'] as $ks=>$vs){
				$goods_info=$p->where(array('goods_no'=>$vs['goods_sn']))->find();
				$list[$k]['order_detail'][$ks]['source_no']=$goods_info['pn'];
				//错误料号9344949001140/9344949001287修正计数器-begin
					if($goods_info['pn']=='9344949001140'){
						if($err_count+$vs['goods_nums']<=72){
							$list[$k]['order_detail'][$ks]['source_no']='9344949001287';
						}
					}
				//错误料号9344949001140/9344949001287修正计数器-end
				
				if(empty($vs['goods_price']) or $vs['goods_price']=='0.00'){
					$list[$k]['order_detail'][$ks]['goods_price']=sprintf("%.2f",$goods_info['price']);
				}else{
					$goods_info['price']=$vs['goods_price'];
				}
				$list[$k]['order_detail'][$ks]['goods_price']=sprintf("%.2f",$goods_info['price']);
				$list[$k]['order_detail'][$ks]['net_weight']=$goods_info['net_weight'];
				$list[$k]['order_detail'][$ks]['gross_weight']=$goods_info['gross_weight'];
				$goods_price=sprintf("%.2f",$goods_info['price']*$vs['goods_nums']);//商品总价格=单价*数量
				// $goods_tax=sprintf("%.2f",$goods_price*$goods_info['goods_tax']);//税金=商品总价格*税率
				$ems_fee=$v['ems_fee'];//运费
				$insure_amount=$v['insure_amount'];//保费
				$consumption_rate=$goods_info['consumption_rate'];//消费税率
				$increment_rate=$goods_info['increment_rate'];//增值税率
				
				$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
				$total_price+=$goods_price;//总价格
				$order_tax+=$goods_tax;//订单总税金
			}
			if(empty($v['buyer_name'])){//购买人为空
				$list[$k]['buyer_name']=$list[$k]['user_name'];
			}
			$discount=empty($v['discount'])?0:$v['discount'];
			$list[$k]['order_amount']=round($total_price+$ems_fee+$insure_amount+$order_tax,2);//申报总价=商品总价+运费+保费-折扣
			$list[$k]['order_tax']=round($order_tax,2);

		}
		$data['data']=$list;

		$u_info=$u->where(array('username'=>$param['username']))->find();
		$data['customer']['user_code']=$u_info['user_code'];
		$data['customer']['user_key']=$u_info['user_key'];

		file_put_contents('./log/cron/pushoms_aozhou_cron'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$res=send_curl($url,$data);
		$res=json_decode($res,true);

		$setstatus['push_status']=1;
		if($res['flag']){
			//错误料号9344949001140/9344949001287修正计数器-begin
			foreach($list as $k=>$v){
				foreach($list[$k]['order_detail'] as $ks=>$vs){
					$goods_info=$p->where(array('goods_no'=>$vs['goods_sn']))->find();
					//错误料号9344949001140/9344949001287修正计数器-begin
						if($goods_info['pn']=='9344949001140'){
							if($err_count+$vs['goods_nums']<=72){
								$err_count+=$vs['goods_nums'];
								$data_count['count']=$err_count;
								$data_count['update_time']=time();
								$m_e->where(array('id'=>1))->save($data_count);
							}
						}
					//错误料号9344949001140/9344949001287修正计数器-end
				}
			}
			//错误料号9344949001140/9344949001287修正计数器-end
			
			$m->where($map)->save($setstatus);
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			return $return;
		}else{
			//更新状态-begin
			foreach($res['data']['detail'] as $ks=>$vs){
				// $map_order['old_order_no'][]=$vs['order_no'];
				if(!empty($vs['logistics_no'])){
					$data_order['logistics_no']=$vs['logistics_no'];
					$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
				}else{
					$old_order_no[]=$vs['order_no'];
				}
			}
			
			//重复订单直接更新推送状态
			if(!empty($old_order_no)){
				$map_order['old_order_no']=array('in',$old_order_no);
				$data_order['push_status']=1;
				$m->where($map_order)->save($data_order);
			}
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=false;
			return $return;
		}
	}
	
	//订单推送(一般正常)
	public function pushoms_normal_normal($param=array(),$db_name){
		$this->erp_db($db_name);
		
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');

		$ids=$param['ids'];
		$url="http://www.t-cang.com/oms/index.php/Api/Request/order_batch";
		$map['id']=array('in',$ids);

		$erp_code=$u->where(array('username'=>$param['username']))->getField('id');//货主erp账号id(erp_code)
		
		$list=$m->field("id,old_order_no order_no,user_name,user_phone,total_price order_amount,province user_province,city user_city,area user_area,user_address,erp_mark_mailno remark,$erp_code erp_code,transport_cate,'ERP' platform_name")->where($map)->select();
		
		foreach($list as $k=>$v){
			$list[$k]['order_detail']=$g->alias('g')->field('g.goods_no goods_sn,p.name goods_name,g.goods_price,g.goods_nums,g.goods_batch_no')->join('__PRODUCT__ p on g.goods_no=p.goods_no','left')->where(array('order_id'=>$v['id']))->group('g.goods_no')->select();
			
			foreach($list[$k]['order_detail'] as $ks=>$vs){
				
				$list[$k]['order_detail'][$ks]['warehouse_code']=I('warehouse_code');
				if(empty($vs['goods_price']) or $vs['goods_price']=='0.00'){
					$list[$k]['order_detail'][$ks]['goods_price']=$p->where(array('goods_no'=>$vs['goods_sn']))->getField('price');
				}
			}
		}
		$data['data']=$list;

		$u_info=$u->where(array('username'=>$param['username']))->find();
		$data['customer']['user_code']=$u_info['user_code'];
		$data['customer']['user_key']=$u_info['user_key'];
		
		$data['trade_model']=0;//非跨境
		file_put_contents('./log/cron/pushoms_normal_normal_cron'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		$res=send_curl($url,$data);
		$res=json_decode($res,true);
		$setstatus['push_status']=1;
		if($res['flag']){
			$m->where($map)->save($setstatus);
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			return $return;
		}else{
			//更新状态-begin
			foreach($res['data']['detail'] as $ks=>$vs){
				// $map_order['old_order_no'][]=$vs['order_no'];
				if(!empty($vs['logistics_no'])){
					$data_order['logistics_no']=$vs['logistics_no'];
					$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
				}else{
					$old_order_no[]=$vs['order_no'];
				}
			}
			
			//重复订单直接更新推送状态
			if(!empty($old_order_no)){
				$map_order['old_order_no']=array('in',$old_order_no);
				$data_order['push_status']=1;
				$m->where($map_order)->save($data_order);
			}
			
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=false;
			return $return;
		}
	}
	//订单推送(跨境正常)
	public function pushoms_normal($param=array(),$db_name){
		$this->erp_db($db_name);
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');
		
		$ids=$param['ids'];
		$url="http://www.t-cang.com/oms/index.php/Api/Request/order_erp";
		$map['id']=array('in',$ids);
		
		$erp_code=$u->where(array('username'=>$param['username']))->getField('id');//货主erp账号id(erp_code)
	
		$list=$m->field("id,old_order_no order_no,user_name,user_phone,user_phone buyer_phone,user_idcard,buyer_idcard,buyer_name,apply_logistics,logiscompany_code,logistics_no,province user_province,city user_city,erp_mark_mailno remark,$erp_code erp_code,area user_area,user_address,pay_number,paycompany_code,discount,ems_fee,ems_fee order_freight,insure_amount,goods_tax,come_from,cod,cod_money,is_mall,alipay_out_trade_no,liandong_apply_no")->where($map)->select();
		// echo $m->getlastsql();
		foreach($list as $k=>$v){
			$list[$k]['order_detail']=$g->alias('g')->field('g.goods_no goods_sn,p.name goods_name,g.goods_nums,g.goods_price,g.goods_batch_no')->join('__PRODUCT__ p on g.goods_no=p.goods_no','left')->where(array('order_id'=>$v['id']))->group('g.goods_no')->select();
			$total_price=0;//订单总价格
			$order_tax=0;//订单总税金
			$total_goods_price=0;//兼容小红书导单
			foreach($list[$k]['order_detail'] as $ks=>$vs){
				$goods_info=$p->where(array('goods_no'=>$vs['goods_sn']))->find();
				$list[$k]['order_detail'][$ks]['source_no']=$goods_info['pn'];
				if(empty($vs['goods_price']) or $vs['goods_price']=='0.00'){
					$list[$k]['order_detail'][$ks]['goods_price']=sprintf("%.2f",$goods_info['price']);
				}else{
					$goods_info['price']=$vs['goods_price'];
				}
				$list[$k]['order_detail'][$ks]['net_weight']=$goods_info['net_weight'];
				$list[$k]['order_detail'][$ks]['gross_weight']=$goods_info['gross_weight'];
				$goods_price=sprintf("%.2f",$goods_info['price']*$vs['goods_nums']);//商品总价格=单价*数量
				// $goods_tax=sprintf("%.2f",$goods_price*$goods_info['goods_tax']);//税金=商品总价格*税率

				$ems_fee=$v['ems_fee'];//运费
				$insure_amount=$v['insure_amount'];//保费
				$consumption_rate=$goods_info['consumption_rate'];//消费税率
				$increment_rate=$goods_info['increment_rate'];//增值税率
				
				$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
				$total_price+=$goods_price;//总价格
				$order_tax+=$goods_tax;//订单总税金
				$total_goods_price+=$goods_price;
			}
			if(empty($v['buyer_name'])){//购买人为空
				$list[$k]['buyer_name']=$list[$k]['user_name'];
			}
			$discount=empty($v['discount'])?0:$v['discount'];
			$list[$k]['order_amount']=round($total_price+$ems_fee+$insure_amount+$order_tax,2);//申报总价=商品总价+运费+保费-折扣
			$list[$k]['set_order_amount']=$list[$k]['order_amount'];
			$list[$k]['order_tax']=round($order_tax,2);
			
		}
		$data['data']=$list;
		
		$u_info=$u->where(array('username'=>$param['username']))->find();
		$data['customer']['user_code']=$u_info['user_code'];
		$data['customer']['user_key']=$u_info['user_key'];
		
		file_put_contents('./log/cron/pushoms_normal_cron'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$res=send_curl($url,$data);
		$res=json_decode($res,true);

		$setstatus['push_status']=1;
		if($res['flag']){
			$m->where($map)->save($setstatus);
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			return $return;
		}else{
			//更新状态-begin
			foreach($res['data']['detail'] as $ks=>$vs){
				// $map_order['old_order_no'][]=$vs['order_no'];
				if(!empty($vs['logistics_no'])){
					$data_order['logistics_no']=$vs['logistics_no'];
					$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
				}else{
					$old_order_no[]=$vs['order_no'];
				}
			}
			
			//重复订单直接更新推送状态
			if(!empty($old_order_no)){
				$map_order['old_order_no']=array('in',$old_order_no);
				$data_order['push_status']=1;
				$m->where($map_order)->save($data_order);
			}
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=false;
			return $return;
		}
	}
}